/**基于小程序登陆授权验证**/

package wechat

import (
	"encoding/json"
	"wxsdk/oauth"
	"wxsdk/miniapp/utils/security"
	"github.com/astaxie/beego"
)

// 代管登陆
func AppletBuyerLogin(appId, isvAccessToken,code, isvAppId, encrytedData, iv string) (userInfo oauth.BuyerUserInfo, err error) {
	sessionInfo := new(oauth.SessionInfo)
	sessionInfo, err = oauth.JsCode2Session(appId, isvAppId, isvAccessToken, code)
	if err != nil {
	    beego.Debug(err.Error())
		return
	}
	decrypted, err := security.WXBizDataDecrypt(sessionInfo.SessionKey, encrytedData, iv)
	if err != nil {
		beego.Debug(err.Error())
		return
	}
	//beego.Debug("AppletBuyerLogin:", string(decrypted))
	err = json.Unmarshal(decrypted, &userInfo)
	if err != nil {
		beego.Debug(err.Error())
		return
	}
	userInfo.SessionKey = sessionInfo.SessionKey
	return
}
// 自管登陆
func AppletSellerLogin(appId,appSecret,code,encrytedData,iv string) (userInfo oauth.BuyerUserInfo, err error) {
	sessionInfo := new(oauth.SessionInfo)
	sessionInfo, err = oauth.JsCode2SessionOwn(appId, appSecret, code)
	if err != nil {
	    beego.Debug(err.Error())
		return
	}
	decrypted, err := security.WXBizDataDecrypt(sessionInfo.SessionKey, encrytedData, iv)
	if err != nil {
		beego.Debug(err.Error())
		return
	}
	//beego.Debug("AppletSellerLogin:", string(decrypted))
	err = json.Unmarshal(decrypted, &userInfo)
	if err != nil {
		beego.Debug(err.Error())
		return
	}
	userInfo.SessionKey = sessionInfo.SessionKey
	return
}
